#!/usr/bin/env python3
import sys, os
from argparse import ArgumentParser

parser = ArgumentParser(description='Converts binary file to Xilinx coe file')

parser.add_argument('infile', help='Input binary file')
parser.add_argument('outfile', help='Output coe file')
parser.add_argument('-d', '--depth', type=int, default=0)
args = parser.parse_args()

with open(args.infile, 'rb') as f:
    depth = os.path.getsize(args.infile)
    if args.depth > 0:
        if args.depth < depth:
            print ("ERROR: Input file is larger than the specified depth!")
            exit (-1)
        depth = args.depth

    with open(args.outfile, 'w') as fmif:
        fmif.write('; Automatically generated by bin2coe.py\n')
        fmif.write('; Translated from ' + args.infile + '\n')
        fmif.write('memory_initialization_radix=16;\n')
        fmif.write('memory_initialization_vector=\n')

        count = 0
        buffer = f.read()
        for b in buffer:
            if count > 0:
                fmif.write(',\n')
            fmif.write('{0:02x}'.format(b))
            count += 1

        while count < depth:
            if count < depth:
                fmif.write(',\n')
            fmif.write('00')
            count += 1
        fmif.write(';\n')
